describe('前端页面缓存操作集成测试', () => {
  let testData

  before(() => {
    cy.fixture('test-data').then((data) => {
      testData = data
    })
  })

  describe('📱 Select页面缓存操作测试', () => {
    beforeEach(() => {
      cy.clearAllCaches()
      cy.visit('http://localhost:8002/#/pages/select/select')
      cy.wait(2000)
    })

    it('应该测试Select页面的缓存清理功能', () => {
      // 先创建一些测试缓存数据
      cy.setupTestCache('smtOrderData', { 
        orderNo: 'TEST123',
        data: 'select_page_test' 
      })
      cy.setupTestCache('tempData1', 'temp_value_1')
      cy.setupTestCache('tempData2', { temp: 'value_2' })
      
      cy.verifyCacheState(['smtOrderData', 'tempData1', 'tempData2'])

      // 填写表单字段
      cy.get('input').then(($inputs) => {
        if ($inputs.length >= 3) {
          cy.get('input').eq(0).clear().type('CACHE_TEST_123')
          cy.get('input').eq(1).clear().type('M05')
          cy.get('input').eq(2).clear().type('1')
          
          cy.log('📝 已填写表单字段')
        }
      })

      // 验证点击开始按钮会触发缓存清理
      cy.get('.btn-start').should('be.visible').click()
      cy.wait(1000)

      // 验证缓存是否被清理 (select.vue:251 uni.clearStorageSync())
      cy.verifyCacheState([], true) // 应该为空
      
      cy.log('✅ Select页面缓存清理验证成功')
    })

    it('应该测试Select页面成功场景的缓存存储', () => {
      // 模拟成功的API响应并验证缓存存储
      cy.intercept('POST', '**/api/smt/initiatePickup', {
        statusCode: 200,
        body: {
          code: '00000',
          message: '操作成功',
          data: {
            orderNo: 'CACHE_SUCCESS_123',
            rollMngNo: 'ROLL_SUCCESS_123',
            partList: [
              {
                partId: 'PART001',
                partName: '测试零件1',
                quantity: 100
              }
            ]
          }
        }
      }).as('successfulInitiate')

      // 填写表单
      cy.get('input').eq(0).clear().type('CACHE_SUCCESS_123')
      cy.get('input').eq(1).clear().type('M05')
      cy.get('input').eq(2).clear().type('1')
      
      // 点击开始按钮
      cy.get('.btn-start').click()
      
      // 等待API调用完成
      cy.wait('@successfulInitiate')
      cy.wait(2000)

      // 验证缓存数据是否被正确存储
      cy.window().then((win) => {
        const cachedData = win.uni.getStorageSync('smtOrderData')
        
        if (cachedData && cachedData.data) {
          expect(cachedData.type).to.equal('object')
          expect(cachedData.data.orderNo).to.equal('CACHE_SUCCESS_123')
          expect(cachedData.data.partList).to.have.length(1)
          
          cy.log('✅ 成功场景缓存存储验证成功')
          cy.log(`📋 缓存订单号: ${cachedData.data.orderNo}`)
          cy.log(`📦 缓存零件数: ${cachedData.data.partList.length}`)
        } else {
          cy.log('⚠️ 成功场景未创建缓存数据或页面已跳转')
        }
      })
    })

    it('应该测试Select页面失败场景的缓存清理', () => {
      // 模拟失败的API响应
      cy.intercept('POST', '**/api/smt/initiatePickup', {
        statusCode: 200,
        body: {
          code: '10000',
          message: '订单不存在',
          data: null
        }
      }).as('failedInitiate')

      // 先创建一些缓存
      cy.setupTestCache('oldData', { old: 'cache_data' })
      cy.verifyCacheState(['oldData'])

      // 填写表单并提交
      cy.get('input').eq(0).clear().type('NONEXISTENT_ORDER')
      cy.get('input').eq(1).clear().type('M05') 
      cy.get('input').eq(2).clear().type('1')
      
      cy.get('.btn-start').click()
      cy.wait('@failedInitiate')
      cy.wait(2000)

      // 验证失败场景下的缓存清理
      cy.verifyCacheState([], true)
      
      cy.log('✅ 失败场景缓存清理验证成功')
    })
  })

  describe('📋 Delivery-Confirm页面缓存操作测试', () => {
    beforeEach(() => {
      cy.clearAllCaches()
      
      // 设置必要的缓存数据用于delivery-confirm页面
      const mockOrderData = {
        type: 'object',
        data: {
          orderNo: `DELIVERY_CACHE_${Date.now()}`,
          rollMngNo: `ROLL_${Date.now()}`,
          partList: [
            {
              partId: 'PART001',
              partName: '测试零件',
              rollNo: 'ROLL001',
              lotNo: 'LOT001',
              quantity: 100
            }
          ]
        }
      }
      
      cy.setupTestCache('smtOrderData', mockOrderData)
    })

    it('应该测试扫码记录的缓存管理', () => {
      const cacheKey = encodeURIComponent('smtOrderData')
      cy.visit(`http://localhost:8002/#/pages/delivery-confirm/delivery-confirm?cacheKey=${cacheKey}`)
      cy.wait(3000)

      cy.window().then((win) => {
        // 验证订单缓存数据被正确读取
        const orderData = win.uni.getStorageSync('smtOrderData')
        expect(orderData).to.not.be.null
        expect(orderData.data.partList).to.have.length(1)
        
        cy.log('✅ 订单缓存数据读取成功')

        // 模拟扫码记录缓存操作
        const scanRecordsKey = 'scanRecords'
        const testScanRecords = [
          {
            partId: 'PART001',
            rollNo: 'ROLL001', 
            scanTime: new Date().toISOString(),
            status: 'success'
          },
          {
            partId: 'PART002',
            rollNo: 'ROLL002',
            scanTime: new Date().toISOString(), 
            status: 'success'
          }
        ]
        
        // 存储扫码记录
        win.uni.setStorageSync(scanRecordsKey, testScanRecords)
        cy.log('📝 存储扫码记录到缓存')
        
        // 验证扫码记录缓存
        const retrievedRecords = win.uni.getStorageSync(scanRecordsKey)
        expect(retrievedRecords).to.have.length(2)
        expect(retrievedRecords[0].partId).to.equal('PART001')
        
        cy.log('✅ 扫码记录缓存验证成功')

        // 模拟添加新扫码记录
        const newRecord = {
          partId: 'PART003',
          rollNo: 'ROLL003',
          scanTime: new Date().toISOString(),
          status: 'failed'
        }
        
        const updatedRecords = [...retrievedRecords, newRecord]
        win.uni.setStorageSync(scanRecordsKey, updatedRecords)
        
        // 验证更新
        const finalRecords = win.uni.getStorageSync(scanRecordsKey)
        expect(finalRecords).to.have.length(3)
        expect(finalRecords[2].status).to.equal('failed')
        
        cy.log('✅ 扫码记录缓存更新验证成功')
      })
    })

    it('应该测试完成流程时的缓存清理', () => {
      const cacheKey = encodeURIComponent('smtOrderData')
      cy.visit(`http://localhost:8002/#/pages/delivery-confirm/delivery-confirm?cacheKey=${cacheKey}`)
      cy.wait(3000)

      // 添加扫码记录缓存
      cy.setupTestCache('scanRecords', [
        { partId: 'PART001', status: 'success' },
        { partId: 'PART002', status: 'success' }
      ])

      cy.verifyCacheState(['smtOrderData', 'scanRecords'])

      // 模拟完成按钮点击（会触发缓存清理）
      cy.get('body').then(($body) => {
        if ($body.find('.btn-complete').length > 0) {
          // 拦截完成API调用
          cy.intercept('POST', '**/api/smt/saveScanRecord', {
            statusCode: 200,
            body: {
              code: '00000',
              message: '保存成功',
              data: {
                successCount: 2,
                failureCount: 0,
                totalCount: 2
              }
            }
          }).as('completeFlow')

          cy.get('.btn-complete').click()
          cy.wait('@completeFlow')
          cy.wait(2000)

          // 验证完成后缓存被清理
          cy.window().then((win) => {
            const remainingCache = win.uni.getStorageInfoSync()
            cy.log(`🔍 完成后剩余缓存键: ${remainingCache.keys.join(', ')}`)
            
            // delivery-confirm.vue:803,806,1117,1119 会清理相关缓存
            const orderCache = win.uni.getStorageSync('smtOrderData')
            const scanCache = win.uni.getStorageSync('scanRecords')
            
            expect(orderCache).to.equal('') // 应该被清理
            expect(scanCache).to.equal('') // 应该被清理
            
            cy.log('✅ 完成流程缓存清理验证成功')
          })
        } else {
          cy.log('⚠️ 未找到完成按钮，跳过完成流程测试')
        }
      })
    })
  })

  describe('👨‍🔧 Operator-Confirm页面缓存操作测试', () => {
    beforeEach(() => {
      cy.clearAllCaches()
      
      // 设置必要的订单数据缓存
      const mockOrderData = {
        type: 'object', 
        data: {
          orderNo: `OPERATOR_CACHE_${Date.now()}`,
          mounterId: 'M05',
          smtSide: '1'
        }
      }
      
      cy.setupTestCache('smtOrderData', mockOrderData)
    })

    it('应该测试作业员确认页面的缓存读取', () => {
      const cacheKey = encodeURIComponent('smtOrderData')
      cy.visit(`http://localhost:8002/#/pages/operator-confirm/operator-confirm?cacheKey=${cacheKey}`)
      cy.wait(3000)

      cy.window().then((win) => {
        // 验证页面能正确读取缓存数据 (operator-confirm.vue:260)
        const cachedData = win.uni.getStorageSync('smtOrderData')
        expect(cachedData).to.not.be.null
        expect(cachedData.data.orderNo).to.include('OPERATOR_CACHE_')
        
        cy.log('✅ 作业员确认页面缓存读取验证成功')
        cy.log(`📋 读取的订单号: ${cachedData.data.orderNo}`)
      })
    })

    it('应该测试作业员确认完成后的缓存清理', () => {
      const cacheKey = encodeURIComponent('smtOrderData')
      cy.visit(`http://localhost:8002/#/pages/operator-confirm/operator-confirm?cacheKey=${cacheKey}`)
      cy.wait(3000)

      // 验证初始缓存存在
      cy.verifyCacheState(['smtOrderData'])

      // 模拟作业员确认API调用
      cy.intercept('POST', '**/api/smt/saveOperatorConfirm', {
        statusCode: 200,
        body: {
          code: '00000',
          message: '确认成功',
          data: {
            processId: `PROCESS_${Date.now()}`
          }
        }
      }).as('operatorConfirm')

      // 填写作业员ID并点击开始
      cy.get('body').then(($body) => {
        if ($body.find('input[placeholder*="作业员"]').length > 0) {
          cy.get('input[placeholder*="作业员"]').type(testData.operators.valid.operatorId)
        } else if ($body.find('input').length > 0) {
          cy.get('input').first().type(testData.operators.valid.operatorId)
        }
        
        if ($body.find('.btn-start').length > 0) {
          cy.get('.btn-start').click()
          cy.wait('@operatorConfirm')
          cy.wait(2000)

          // 验证成功场景下缓存清理 (operator-confirm.vue:233)
          cy.window().then((win) => {
            const orderCache = win.uni.getStorageSync('smtOrderData')
            // 成功场景下可能缓存被清理或保留，取决于具体业务逻辑
            cy.log(`📊 确认成功后缓存状态: ${orderCache === '' ? '已清理' : '保留'}`)
          })
        }
      })
    })
  })

  describe('🗂️ 缓存管理器工具测试', () => {
    it('应该测试cacheManager工具的缓存操作', () => {
      cy.window().then((win) => {
        // 测试cacheManager中定义的缓存键
        const smtOrderData = {
          orderNo: `MANAGER_TEST_${Date.now()}`,
          rollMngNo: `ROLL_${Date.now()}`,
          partList: [
            {
              partId: 'MANAGER_PART001',
              partName: '缓存管理器测试零件',
              quantity: 50
            }
          ]
        }

        // 使用标准SMT缓存键存储数据
        const cacheKey = 'smtOrderData' // CACHE_KEYS.SMT_ORDER_DATA
        const dataToStore = {
          type: 'object',
          data: smtOrderData
        }
        
        win.uni.setStorageSync(cacheKey, dataToStore)
        cy.log('📦 使用cacheManager格式存储数据')

        // 验证数据存储格式
        const retrievedData = win.uni.getStorageSync(cacheKey)
        expect(retrievedData.type).to.equal('object')
        expect(retrievedData.data.orderNo).to.include('MANAGER_TEST_')
        expect(retrievedData.data.partList).to.have.length(1)
        
        cy.log('✅ cacheManager格式验证成功')

        // 测试旧格式缓存清理
        const oldCacheKeys = [
          'delivery_data_old1',
          'bom_old_data_test',
          'smtOrderData_legacy'
        ]
        
        oldCacheKeys.forEach(key => {
          win.uni.setStorageSync(key, { old: 'data' })
        })
        
        cy.log('🗂️ 创建旧格式缓存数据')
        
        // 模拟旧缓存清理逻辑
        const storageInfo = win.uni.getStorageInfoSync()
        const keysToRemove = storageInfo.keys.filter(key => 
          key.startsWith('delivery_data_') || 
          key.startsWith('smtOrderData_') ||
          key.match(/^bom_.*_.*_.*$/)
        )
        
        cy.log(`🧹 找到${keysToRemove.length}个旧缓存键: ${keysToRemove.join(', ')}`)
        
        keysToRemove.forEach(key => {
          win.uni.removeStorageSync(key)
        })
        
        // 验证清理结果
        const afterCleanup = win.uni.getStorageInfoSync()
        keysToRemove.forEach(key => {
          expect(afterCleanup.keys).to.not.include(key)
        })
        
        // 但标准缓存应该保留
        expect(afterCleanup.keys).to.include('smtOrderData')
        
        cy.log('✅ 旧缓存清理验证成功')
      })
    })

    it('应该测试缓存数据的并发操作', () => {
      cy.window().then((win) => {
        const baseKey = 'concurrencyTest'
        const concurrentOps = []
        
        // 创建并发缓存操作
        for (let i = 0; i < 10; i++) {
          const key = `${baseKey}_${i}`
          const data = {
            id: i,
            timestamp: Date.now(),
            data: `concurrent_test_${i}`
          }
          
          concurrentOps.push(() => {
            win.uni.setStorageSync(key, data)
            return win.uni.getStorageSync(key)
          })
        }
        
        cy.log('🔄 执行并发缓存操作')
        
        // 执行所有并发操作
        const results = concurrentOps.map(op => op())
        
        // 验证所有操作都成功
        results.forEach((result, index) => {
          expect(result.id).to.equal(index)
          expect(result.data).to.equal(`concurrent_test_${index}`)
        })
        
        cy.log('✅ 并发缓存操作验证成功')
        
        // 验证所有缓存键都存在
        const storageInfo = win.uni.getStorageInfoSync()
        for (let i = 0; i < 10; i++) {
          expect(storageInfo.keys).to.include(`${baseKey}_${i}`)
        }
        
        cy.log(`📊 并发创建${results.length}个缓存项验证成功`)
        
        // 清理并发测试缓存
        for (let i = 0; i < 10; i++) {
          win.uni.removeStorageSync(`${baseKey}_${i}`)
        }
        
        cy.log('🧹 并发测试缓存清理完成')
      })
    })
  })

  describe('⚡ 缓存性能和稳定性测试', () => {
    it('应该测试大容量缓存数据的性能', () => {
      cy.testCachePerformance(500).then((result) => {
        if (result) {
          expect(result.writeTime).to.be.lessThan(1000) // 写入应在1秒内
          expect(result.readTime).to.be.lessThan(500)   // 读取应在0.5秒内
          expect(result.dataSize).to.equal(500)
          
          cy.log('✅ 大容量缓存性能测试通过')
        }
      })
    })

    it('应该测试缓存边界条件', () => {
      cy.window().then((win) => {
        // 测试空值缓存
        win.uni.setStorageSync('emptyTest', '')
        const emptyResult = win.uni.getStorageSync('emptyTest')
        expect(emptyResult).to.equal('')
        cy.log('✅ 空值缓存测试通过')

        // 测试null值缓存  
        win.uni.setStorageSync('nullTest', null)
        const nullResult = win.uni.getStorageSync('nullTest')
        expect(nullResult).to.equal(null)
        cy.log('✅ null值缓存测试通过')

        // 测试undefined值缓存
        win.uni.setStorageSync('undefinedTest', undefined) 
        const undefinedResult = win.uni.getStorageSync('undefinedTest')
        // UniApp可能将undefined转换为null或空字符串
        cy.log(`📝 undefined缓存结果: ${JSON.stringify(undefinedResult)}`)

        // 测试复杂JSON数据
        const complexJson = {
          array: [1, 2, 3, { nested: 'value' }],
          object: { deep: { very: { nested: 'data' } } },
          string: 'test',
          number: 42,
          boolean: true,
          date: new Date().toISOString()
        }
        
        win.uni.setStorageSync('complexJsonTest', complexJson)
        const complexResult = win.uni.getStorageSync('complexJsonTest')
        
        expect(complexResult.array).to.have.length(4)
        expect(complexResult.object.deep.very.nested).to.equal('data')
        expect(complexResult.number).to.equal(42)
        expect(complexResult.boolean).to.equal(true)
        
        cy.log('✅ 复杂JSON数据缓存测试通过')

        // 清理测试数据
        ['emptyTest', 'nullTest', 'undefinedTest', 'complexJsonTest'].forEach(key => {
          win.uni.removeStorageSync(key)
        })
      })
    })

    it('应该测试缓存异常处理和恢复', () => {
      cy.window().then((win) => {
        // 测试非法键名处理
        const invalidKeys = ['', null, undefined, 123, {}, []]
        
        invalidKeys.forEach((invalidKey, index) => {
          try {
            win.uni.setStorageSync(invalidKey, `test_${index}`)
            cy.log(`⚠️ 非法键名"${invalidKey}"被接受`)
          } catch (error) {
            cy.log(`✅ 非法键名"${invalidKey}"被正确拒绝: ${error.message}`)
          }
        })

        // 测试缓存溢出处理（创建大量数据直到接近限制）
        const storageInfo = win.uni.getStorageInfoSync()
        const currentUsage = (storageInfo.currentSize / storageInfo.limitSize) * 100
        
        cy.log(`📊 当前缓存使用率: ${currentUsage.toFixed(2)}%`)
        
        if (currentUsage < 80) {
          // 如果使用率不高，创建一些大数据测试
          const largeTestData = new Array(2000).fill(0).map((_, i) => ({
            id: i,
            data: `large_cache_test_${i}`.repeat(10), // 增加数据大小
            timestamp: Date.now()
          }))
          
          try {
            win.uni.setStorageSync('largeDataTest', largeTestData)
            
            const afterLarge = win.uni.getStorageInfoSync()
            const newUsage = (afterLarge.currentSize / afterLarge.limitSize) * 100
            
            cy.log(`📈 大数据后使用率: ${newUsage.toFixed(2)}%`)
            
            // 清理大数据
            win.uni.removeStorageSync('largeDataTest')
            
            cy.log('✅ 大容量缓存测试完成')
          } catch (error) {
            cy.log(`⚠️ 缓存容量限制触发: ${error.message}`)
          }
        }
      })
    })
  })
})